/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.grass.plugin.dialect;

import com.grass.plugin.paging.page.Page;

/**
 *
 * @author wujx
 * QQ 396246973
 * Date 2013-02-10
 */
public class DB2Dialect extends Dialect {

	@Override
    public String getLimitString(String sql, Page page) {
        if (page.isPagination() == false) {
            return sql;
        }
        int startOfSelect = sql.toLowerCase().indexOf("select");
        StringBuffer pagingSelect = new StringBuffer(sql.length() + 100)
                .append(sql.substring(0, startOfSelect)) // add the comment
                .append("select * from ( select ") // nest the main query in an outer select
                .append(getRowNumber(sql)); // add the rownnumber bit into the outer query select list
        if (hasDistinct(sql)) {
            pagingSelect.append(" row_.* from ( ") // add another (inner) nested select
                    .append(sql.substring(startOfSelect)) // add the main query
                    .append(" ) as row_"); 					// close off the inner nested select
        } else {
            pagingSelect.append(sql.substring(startOfSelect + 6)); // add the main query
        }
        pagingSelect.append(" ) as temp_ where rownumber_ ");
        pagingSelect.append("between ").append(page.getPageStartRow()).append(" + 1").append(" and ").append(page.getPageEndRow());
        return pagingSelect.toString();
    }

    private String getRowNumber(String sql) {
        StringBuffer rownumber = new StringBuffer(50).append("rownumber() over(");
        int orderByIndex = sql.toLowerCase().indexOf("order by");
        if (orderByIndex > 0 && !hasDistinct(sql)) {
            rownumber.append(sql.substring(orderByIndex));
        }
        rownumber.append(") as rownumber_,");
        return rownumber.toString();
    }
    
    @Override
	public String Escape(String sql,String lmark, String rmark) {	   
		return sql.replaceAll(lmark == null? "\\[" : lmark, "\\\"").replaceAll(rmark == null? "\\]" : rmark, "\\\"");
	}
}
